import React from 'react';
import {
    Text,
    View,
    ScrollView,
    Button,
} from 'react-native';
import RNFetchBlob from 'react-native-fetch-blob'
import L from "../util/L";

let IP_PORT = "192.168.1.4:8080";
/** 下载到手机目录 */
let DIR_DOWN_PATH = RNFetchBlob.fs.dirs.SDCardDir + '/rntest/';

/** 网络 */
export default class PageNet extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            mInfo: "Welcome",
        };
    }

    render() {
        return (
            <ScrollView>
                <View>
                    <View style={{height: 15, backgroundColor: 'white', opacity: 0.5}}/>
                    <Button
                        title="Get"
                        onPress={() => this._Get()}/>

                    <View style={{height: 15, backgroundColor: 'white', opacity: 0.5}}/>
                    <Button
                        title="Post-传统传参数"
                        onPress={() => this._Post()}/>

                    <View style={{height: 15, backgroundColor: 'white', opacity: 0.5}}/>
                    <Button
                        title="Post-JSON传参数"
                        onPress={() => this._PostJson()}/>

                    <View style={{height: 15, backgroundColor: 'white', opacity: 0.5}}/>
                    <Button
                        title="FetchBlob下载图片到SD"
                        onPress={() => this._fetchBlob_DownImg_To_SD()}/>

                    <View style={{height: 15, backgroundColor: 'white', opacity: 0.5}}/>
                    <Button
                        title="FetchBlob从SD上传"
                        onPress={() => this._fetchBlob_Upload_From_SD()}/>

                    <View style={{height: 15, backgroundColor: 'white', opacity: 0.5}}/>
                    <Text>{this.state.mInfo}</Text>
                </View>
            </ScrollView>
        );
    }

    /** get */
    _Get(): void {
        this.setState({mInfo: '开始查询...'});
        fetch(
            'http://' + IP_PORT + '/MyUrlSample/testrequest?usename=XJS',
            {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
            })
            .then((response) => response.text())
            .then((jsonStr) => {
                this.setState({mInfo: jsonStr});
                L.logAndWrite('123', "查询结果", jsonStr);
            })
            .catch((error) => {
                this.setState({mInfo: '查询失败，' + error});
            })
    }

    /** 普通body参数 */
    _Post(): void {
        this.setState({mInfo: '开始查询...'});
        fetch(
            'http://' + IP_PORT + '/MyUrlSample/testrequest',
            {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'usename=xjs'
            })
            .then((response) => response.text())
            .then((jsonStr) => {
                this.setState({mInfo: jsonStr});
            })
            .catch((error) => {
                this.setState({mInfo: '查询失败，' + error});
            })
    }

    /** json格式化Body参数 */
    _PostJson(): void {
        this.setState({mInfo: '开始查询...'});
        fetch(
            'http://' + IP_PORT + '/MyUrlSample/testjsonrequest',
            {
                method: 'POST',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json; charset=utf-8',
                },
                body: JSON.stringify({
                    usename: 'xjs',
                })
            })
            .then((response) => response.text())
            .then((jsonStr) => {
                this.setState({mInfo: jsonStr});
            })
            .catch((error) => {
                this.setState({mInfo: '查询失败，' + error});
                console.log("error", error);
            })
    }

    /** 框架下载(放入SD) */
    _fetchBlob_DownImg_To_SD() {
        this.setState({mInfo: '开始下载...'});
        // send http request in a new thread (using native code)
        let task = RNFetchBlob
            .config({
                path: DIR_DOWN_PATH + 'pdf_heave.pdf',
            })
            .fetch(
                'GET',
                'http://' + IP_PORT + '/MyUrlSample/pdf_heave.pdf',
                {
                    // [header]
                    Authorization: 'Bearer access-token...',
                }
            );

        // listen to download progress event
        task
            .progress((received, total) => {
                this.setState({mInfo: '下载中' + (received / total)});
            })
            .then((res) => {
                this.setState({mInfo: '下载完成'});
            })
            .catch((errorMessage, statusCode) => {
                // Status code is not 200, error handling
                this.setState({mInfo: '下载失败, errorMessage:' + errorMessage});
            });

        // task.cancel((err) => {});
    }

    /** 框架上传(支持多文件) */
    _fetchBlob_Upload_From_SD() {
        this.setState({mInfo: '开始上传...'});
        let task = RNFetchBlob
            .fetch(
                'POST',
                'http://' + IP_PORT + '/MyUrlSample/upload',
                {
                    // [header]
                    Authorization: "Bearer access-token",
                    otherHeader: "foo",
                    'Content-Type': 'multipart/form-data',
                },
                [
                    // [body]上传SD卡文件
                    {
                        name: 'pdf_heave',
                        filename: 'pdf_heave.pdf',
                        data: RNFetchBlob.wrap(DIR_DOWN_PATH + 'pdf_heave.pdf')
                    },
                    // [body]上传长文本/Json
                    {name: 'name', data: 'user'},
                    {
                        name: 'info', data: JSON.stringify({
                            mail: 'example@example.com',
                            tel: '12345678'
                        })
                    },
                ]);

        task
            .uploadProgress((written, total) => {
                this.setState({mInfo: '上传中' + (written / total)});
            })
            .then((resp) => {
                this.setState({mInfo: '上传结束'});
            })
            .catch((err) => {
                this.setState({mInfo: '上传失败, err:' + err});
            })

        // task.cancel((err) => {});
    }

}


